<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Models\Channel;
use App\Models\FrontendUser;
use DB;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;
use Vinlon\Laravel\LayAdmin\PaginateResponse;

class ChannelDashboardController
{
    public function listChannels()
    {
        $channel = Channel::query()->where('uuid', request()->channel_code)->first();
        $channelId = -1;
        if ($channel) {
            $channelId = $channel->id;
            if ($channel->mobile != request()->mobile) {
                throw new AdminException('手机号和渠道码不匹配');
            }
        }

        $query = Channel::query()->where('parent_id', $channelId)->orWhere('id', $channelId);
        $count = $query->count();
        $page = request()->get('page', 0);
        $limit = request()->get('limit', 10); //如果没有设置limit，则默认只查询10条记录
        $list = $query->offset($limit * ($page - 1))->limit($limit)->get();
        $channelIds = \Arr::pluck($list, 'id');
        $userSummary = $this->channelUserSummary($channelIds);
        $orderSummary = $this->channelOrderSummary($channelIds);
        foreach ($list as &$row) {
            $channelId = $row->id;
            $row['user_count'] = \Arr::get($userSummary, $channelId . '.user_count', 0);
            $row['real_user_count'] = \Arr::get($userSummary, $channelId . '.real_user_count', 0);
            $row['order_count'] = \Arr::get($orderSummary, $channelId . '.order_count', 0);
            $row['order_amount'] = toYuan(\Arr::get($orderSummary, $channelId . '.order_amount', 0));
        }
        //查询用户和订单数据
        return new PaginateResponse($count, $list);
    }

    public function listChannelUsers()
    {
        $channel = Channel::query()->where('uuid', request()->channel_code)->first();
        $channelId = -1;
        if ($channel) {
            $channelId = $channel->id;
            if ($channel->mobile != request()->mobile) {
                throw new AdminException('手机号和渠道码不匹配');
            }
        }
        $userOrderSummary = $this->userOrderSummary([$channelId]);
        $query = FrontendUser::query()->with(['auth'])->where('channel_id', $channelId);

        return paginate_result($query, function (FrontendUser $user) use ($userOrderSummary) {
            $user->order_summary = \Arr::get($userOrderSummary, $user->id);

            return $user;
        });
    }

    private function channelUserSummary($channelIds)
    {
        if (empty($channelIds)) {
            return [];
        }
        $ids = implode(',', $channelIds);
        $users = DB::select("
            SELECT a.channel_id,count(a.id)as user_count, COUNT(b.id) as real_user_count
            FROM op_frontend_users AS a
            LEFT JOIN op_user_auths AS b ON a.id = b.user_id
            WHERE a.channel_id IN({$ids}) GROUP BY a.channel_id
        ");
        $userData = [];
        foreach ($users as $user) {
            if (!isset($userData[$user->channel_id])) {
                $userData[$user->channel_id] = [];
            }
            $userData[$user->channel_id]['user_count'] = $user->user_count;
            $userData[$user->channel_id]['real_user_count'] = $user->real_user_count;
        }

        return $userData;
    }

    private function channelOrderSummary($channelIds)
    {
        if (empty($channelIds)) {
            return [];
        }
        $ids = implode(',', $channelIds);
        $orders = DB::select("
            SELECT c.channel_id , count(*) AS order_count , sum(order_amount) AS order_amount
            FROM op_orders AS a
            INNER JOIN op_products AS b ON a.product_id = b.id
            INNER JOIN op_frontend_users AS c ON a.user_id = c.id
            WHERE a.order_status = 'paid' AND c.channel_id IN({$ids}) GROUP BY c.channel_id
        ");
        $orderData = [];
        foreach ($orders as $order) {
            $orderData[$order->channel_id]['order_amount'] = $order->order_amount;
            $orderData[$order->channel_id]['order_count'] = $order->order_count;
        }

        return $orderData;
    }

    private function userOrderSummary($channelIds)
    {
        if (empty($channelIds)) {
            return [];
        }
        $ids = implode(',', $channelIds);
        $list = DB::select("
            SELECT c.id ,b.name, count(*) AS order_count , sum(order_amount) AS order_amount
            FROM op_orders AS a
            INNER JOIN op_products AS b ON a.product_id = b.id
            INNER JOIN op_frontend_users AS c ON a.user_id = c.id
            WHERE a.order_status = 'paid' AND c.channel_id IN({$ids}) GROUP BY c.id, b.name
        ");
        $orderData = [];
        foreach ($list as $row) {
            $orderData = \Arr::add($orderData, $row->id . '.order_amount', 0);
            $orderData = \Arr::add($orderData, $row->id . '.order_count', 0);
            $orderData[$row->id]['order_amount'] += toYuan($row->order_amount);
            $orderData[$row->id]['order_count'] += $row->order_count;
            $orderData[$row->id]['per_product'][$row->name]['order_amount'] = toYuan($row->order_amount);
            $orderData[$row->id]['per_product'][$row->name]['order_count'] = $row->order_count;
        }

        return $orderData;
    }
}
